import React, { useEffect, useState } from 'react'
import {
  Form,
  Select,
  Button,
  Row,
  Col,
  DatePicker,
  Popover,
  Empty,
  List,
  Avatar,
  Card,
  Statistic,
  message
} from 'antd'
import { dateType, getLabelList, hazardLevelOptions } from '../../../main/common/localDict'
import MZ from '../assets/maozhao.svg'
import dayjs from 'dayjs'
import maomi1Gif from '../assets/maomi-1.gif'
import CountUp from 'react-countup'
import {
  IVulnerabilityInformationListData,
  IVulnerabilityInformationListParams
  // IVulnerabilityInformationListRecord
} from '../../../types'
import * as ld from 'lodash'
const formatter = (value: number | string) => <CountUp end={value as number} separator="," />

const VulnerabilityInformationList: React.FC<any> = () => {
  const [data, setData] = useState<IVulnerabilityInformationListData>()
  const [loading, setLoading] = useState<boolean>(false)
  const [isExoprting, setIsExportTing] = useState<boolean>(false)
  const [cacheList, setCacheList] = useState<IVulnerabilityInformationListParams[]>([])
  const [messageApi, contextHolder] = message.useMessage()
  const [filterParams, setFilterParams] = useState<IVulnerabilityInformationListParams>({
    beginTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
    dateType: 'publishTime',
    endTime: dayjs().format('YYYY-MM-DD'),
    hazardLevel: '1',
    keyword: '',
    pageIndex: 1,
    pageSize: 10,
    product: '',
    vendor: '',
    vulType: '',
    total: 0
  })
  const fetchList = () => {
    /**
     *setTimeout 优化 window.electron.ipcRenderer.sendSync 导致的 几毫米的卡顿！
     */
    setLoading(true)
    const timer = setTimeout(async () => {
      const res = await window.electron.ipcRenderer.sendSync('getVulnerList', filterParams)
      filterParams.total = res.total
      setData(res)
      setLoading(false)
      clearTimeout(timer)
    }, 500)
  }
  useEffect(() => {
    fetchList()
  }, [filterParams])
  const formCallBack = (e: any, type: keyof IVulnerabilityInformationListParams) => {
    setFilterParams((v: IVulnerabilityInformationListParams) => {
      if (type === 'beginTime') {
        filterParams.beginTime = e ? dayjs(e[0]).format('YYYY-MM-DD') : ''
        filterParams.endTime = e ? dayjs(e[1]).format('YYYY-MM-DD') : ''
      } else {
        // @ts-ignore
        v[type] = e
      }
      return ld.cloneDeepWith(v)
    })
  }
  const removeCatchIndex = (index: number) => {
    cacheList.splice(index, 1)
    setCacheList(ld.cloneWith(cacheList))
  }
  const renderCacheList = () => {
    return (
      <div>
        <p>当前已经缓存的条件列表</p>
        {cacheList.length > 0 ? (
          cacheList.map((v, index) => {
            return (
              <Card key={index}>
                <Button size="small">数量:{v.total}</Button>
                <Button size="small">级别:{getLabelList(v.hazardLevel, hazardLevelOptions)}</Button>
                <Button size="small">
                  {getLabelList(v.dateType, dateType)}:{v.beginTime}——
                  {v.endTime}
                </Button>
                <Button size="small" type="link" onClick={() => removeCatchIndex(index)}>
                  删除
                </Button>
              </Card>
            )
          })
        ) : (
          <Empty />
        )}
      </div>
    )
  }
  const handleExports = () => {
    setIsExportTing(true)
    const timer = setTimeout(async () => {
      await window.electron.ipcRenderer.sendSync(
        'exportVulnerabilityInformationList',
        cacheList.length > 0 ? cacheList : [filterParams]
      )
      setIsExportTing(false)
      clearTimeout(timer)
    }, 500)
  }
  const handleCacheCondition = () => {
    if (
      !filterParams.hazardLevel &&
      !filterParams.dateType &&
      !filterParams.beginTime &&
      !filterParams.endTime
    ) {
      messageApi.warning('无可缓存的条件喔~')
      return
    }
    const hasInCache = cacheList.find((v) => {
      return (
        v.hazardLevel === filterParams.hazardLevel &&
        v.dateType === filterParams.dateType &&
        v.beginTime === filterParams.beginTime &&
        v.endTime === filterParams.endTime
      )
    })
    if (hasInCache) {
      messageApi.warning('重复条件请不要添加了喔~')
      return
    }
    setCacheList([...cacheList, ld.cloneDeepWith(filterParams)])
  }
  return (
    <>
      {contextHolder}
      <Form wrapperCol={{ span: 16 }}>
        <Row>
          <Col xs={24} md={12} lg={12}>
            <Form.Item initialValue={filterParams.hazardLevel} label="危害等级" name="hazardLevel">
              <Select
                allowClear={true}
                value={filterParams.hazardLevel}
                size="large"
                onChange={(e) => formCallBack(e, 'hazardLevel')}
                options={hazardLevelOptions}
              />
            </Form.Item>
          </Col>
          <Col xs={24} md={12} lg={12}>
            <Form.Item initialValue={filterParams.dateType} label="时间类型" name="dateType">
              <Select
                size="large"
                onChange={(e) => formCallBack(e, 'dateType')}
                options={dateType}
              />
            </Form.Item>
          </Col>
          <Col xs={24} md={12} lg={12}>
            <Form.Item label="查询时间">
              <DatePicker.RangePicker
                defaultValue={[dayjs(filterParams.beginTime), dayjs(filterParams.endTime)]}
                onChange={(e) => formCallBack(e, 'beginTime')}
                style={{ width: '100%' }}
                size="large"
              />
            </Form.Item>
          </Col>
          <Col xs={24} md={12} lg={12}>
            <Form.Item>
              <div className="flex">
                <Popover
                  title="按钮说明:导出数据"
                  content={
                    <div>
                      <img
                        width="70px"
                        height="70px"
                        style={{ borderRadius: '50%', verticalAlign: 'middle' }}
                        src={maomi1Gif}
                      />
                      <span style={{ fontSize: '16px' }}>
                        有缓存条件则按照条件导出！否则按照当前条件导出全部数据！
                      </span>
                    </div>
                  }
                >
                  <Button
                    loading={isExoprting}
                    size="large"
                    type="default"
                    icon={<img src={MZ} style={{ verticalAlign: 'middle' }} width="30px" alt="" />}
                    className="flex items-center"
                    onClick={handleExports}
                  >
                    <span style={{ color: '#e0a0b1', margin: '0 10px' }}>Export</span>
                  </Button>
                </Popover>
                <Popover
                  title="按钮说明:(点击我缓存当前搜索条件，导出时可以导出缓存条件的全部数据)"
                  content={renderCacheList()}
                  placement="top"
                >
                  <Button
                    size="large"
                    type="default"
                    icon={<img src={MZ} style={{ verticalAlign: 'middle' }} width="30px" alt="" />}
                    className="flex items-center"
                    onClick={handleCacheCondition}
                  >
                    <span style={{ color: '#e0a0b1', margin: '0 10px' }}>Cache</span>
                  </Button>
                </Popover>
              </div>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <List
        loading={loading}
        pagination={{
          position: 'top',
          align: 'start',
          showTotal: (total) => (
            <Statistic formatter={formatter} title="当前条件漏洞数量" value={total} />
          ),
          pageSize: filterParams.pageSize,
          current: filterParams.pageIndex,
          total: data?.total,
          onChange: (page: number, pageSize: number) => {
            filterParams.pageIndex = page
            filterParams.pageSize = pageSize
            setFilterParams(ld.cloneDeepWith(filterParams))
          }
        }}
        bordered={true}
        size={'small'}
        dataSource={data?.records}
        rowKey="id"
        renderItem={(item) => (
          <List.Item
            actions={
              [
                // <Button type="link" key="list-loadmore-edit">
                //   WATCH
                // </Button>
              ]
            }
          >
            <List.Item.Meta
              avatar={<Avatar>{getLabelList(item.hazardLevel, hazardLevelOptions)}</Avatar>}
              title={<a href="#">{item.vulName}</a>}
              description={item.cnnvdCode}
            />
            <span style={{ color: 'gray' }}>收录时间:{item.publishTime}</span>
          </List.Item>
        )}
      ></List>
    </>
  )
}

export default VulnerabilityInformationList
